﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Sql;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using System.Threading;
using System.Collections.ObjectModel;

namespace Organizer
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    /// 
     
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            tabl = new Statistic();
            TaskList = new ObservableCollection<Task>();
            InitializeComponent();
            if (DataBase.checkDB())
            {
                TaskList = DataBase.Gets();
                TaskListBox.ItemsSource = TaskList;
                tabl = DataBase.GetStats();
            }
            else
            {
                DataBase.creatBD();
                DataBase.BaseStats(tabl);
            }
        }

        bool flag = false;
        bool isSelectedItem = false;
        int[] mas = new int[100];
        static Thread timeThread=null;
        TimeSpan t;
        myTime[] curTime = new myTime [100];

        static Statistic tabl;
        static Task SelectedTask;
        static bool isGointTask = false;
        static int numRunTask = 0;
        private DateTime beforeTime;

        private bool doDelete = false;
        private int deleteIndex = 0;

        private ObservableCollection<Task> TaskList;

        private System.Windows.Forms.NotifyIcon TrayIcon = null;
        private System.Windows.Controls.ContextMenu TrayMenu = null;
        private WindowState fCurrentWindowState = WindowState.Normal;
        public WindowState CurrentWindowState
        {
            get { return fCurrentWindowState; }
            set { fCurrentWindowState = value; }
        }
        private void ShowHideMainWindow(object sender, RoutedEventArgs e)
        {
            TrayMenu.IsOpen = false;
            if (IsVisible)
            {
                Hide();
                (TrayMenu.Items[0] as MenuItem).Header = "Show";
                TrayIcon.Visible = true;
            }
            else
            {
                Show();
                (TrayMenu.Items[0] as MenuItem).Header = "Hide";
                WindowState = CurrentWindowState;
                Activate();
                TrayIcon.Visible = false;
               }
        }
        private bool createTrayIcon() //2
        {
            bool result = false;
            if (TrayIcon == null)
            {
                TrayIcon = new System.Windows.Forms.NotifyIcon(); // создаем 
                TrayIcon.Icon = Organizer.Properties.Resources.Death_List; // изображение для трея
                TrayIcon.Text = "Here is tray icon text."; // текст подсказки, всплывающей над иконкой

                //if (SelectedTask != null)
                //    if (SelectedTask.isRun)
                //        TrayIcon.Text = SelectedTask.name;
                //    else
                //        if (isGointTask)
                //            TrayIcon.Text = "Task in process";
                //        else
                //            TrayIcon.Text = "There is not tasks in process";
                //else
                //    TrayIcon.Text = "Let's go!";

                TrayMenu = Resources["TrayMenu"] as ContextMenu; // а здесь уже ресурсы окна и тот самый x:Key
                TrayIcon.Click += delegate(object sender, EventArgs e)
                {
                    if ((e as System.Windows.Forms.MouseEventArgs).Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        // событие по левой кнопке 
                        ShowHideMainWindow(sender, null);
                       // TrayIcon.Visible = false;
                    }
                    else
                    {
                        // событие по правой кнопке и всем остальным
                        TrayMenu.IsOpen = true;
                        Activate(); // отдаём окну фокус
                    }
                };
                result = true;
            }
            else
            { 
                result = true;
            }
        //    TrayIcon.Visible = true; // делаем иконку видимой в трее
              TrayIcon.Visible = false;
            return result;
        }
        protected override void OnStateChanged(EventArgs e)
        {
            base.OnStateChanged(e); // системная обработка
            if (this.WindowState == System.Windows.WindowState.Minimized)
            {
                // если окно минимизировали, просто спрячем
                Hide();
                // и поменяем надпись на менюшке
                (TrayMenu.Items[0] as MenuItem).Header = "Show";
            }
            else
            {
                // в противном случае запомним текущее состояние
                CurrentWindowState = WindowState;
            }
        }
        protected override void OnSourceInitialized(EventArgs e) //1
        {
            base.OnSourceInitialized(e);
            createTrayIcon(); // создание иконки
        }
        private bool fCanClose = false;
        public bool CanClose
        {
            get { return fCanClose; }
            set { fCanClose = value; }
        }
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e); // встроенная обработка
            if(!CanClose) 
            {    
                e.Cancel = true;
                CurrentWindowState = this.WindowState;
                (TrayMenu.Items[0] as MenuItem).Header = "Show";
                TrayIcon.Visible = true;
                Hide();
            }
            else 
            { 
                TrayIcon.Visible = false;
            }
        }     

        private void MenuExitClick(object sender, RoutedEventArgs e)
        {
            CanClose = true;
            Close();
        }
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            Pause(true);
            forStats();
            if (timeThread != null)
            {
                timeThread.Abort();
                timeThread = null;
            }
            Application.Current.Shutdown();
        }
        private void About_Click(object sender, RoutedEventArgs e)
        {
            var wind = new About();
            wind.ShowDialog();
        }
        private void Stats_Click(object sender, RoutedEventArgs e)
        {
            forStats();
            var wind = new Statistica(tabl);
            wind.ShowDialog();
        }
        private void Help_Click(object sender, RoutedEventArgs e)
        {
            var wind = new Help();
            wind.ShowDialog();
        }

        private void forStats()
        {
            tabl.processesTasks = TaskList.Count;
            DataBase.StatsAdd(tabl);
            DataBase.StatsPause(tabl);
            DataBase.StatsComplete(tabl);
        }

        private void New_Click(object sender, RoutedEventArgs e)
        {
            before();
            Task tmp = new Task();
            int MaxIndex = TaskListBox.Items.Count;
            int SelectedIndex = TaskListBox.SelectedIndex;;
            bool isClearList = false;

            if (TaskListBox.SelectedItem == null)
                isClearList = true;

            var wind = new Create(tmp);
            wind.ShowDialog();

            ReDrow();

            if (DataBase.isName)   // new task
            {
                DataBase.isName = false;
                //TaskList.Add(tmp);
                tabl.Add(tmp);
                TaskListBox.SelectedIndex = MaxIndex;
            }
            else                  // no task
                if (!isClearList)
                {
                    TaskListBox.SelectedIndex = SelectedIndex;
                    ListBoxSelectedChange();
                }
           
            after();
            TaskListBox.Focus();
        }
        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            before();
            Task tmp = (Task)TaskListBox.SelectedItem;
            if (tmp != null)
            {
                int SelectedIndex = TaskListBox.SelectedIndex;

                var wind = new Create(tmp);
                wind.Title = "Edit";
                wind.ShowDialog();

                ReDrow();

                TaskListBox.SelectedIndex = SelectedIndex;
                ListBoxSelectedChange();
                TaskListBox.Focus();
                ButtonEnable();
            }
            after();
        }
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            Delete();            
        }
        private void Delete()
        {
            doDelete = true;
            if (TaskListBox.SelectedItem != null)
            {
                before();
                Task tmp = (Task)TaskListBox.SelectedItem;
                deleteIndex = TaskListBox.SelectedIndex;
                DataBase.Delete(tmp);
                ReDrow();
                TaskListBox.SelectedIndex = TaskListBox.Items.Count - 1;
                if (TaskListBox.Items.Count == 0)
                    isSelectedItem = false;
                ButtonEnable();
                TaskListBox.Focus();
                after();
            }
            if (TaskListBox.Items.Count == 0)
            {
                taskNameTB.Text = "";
                taskDefinitionTB.Text = "";
                taskStartDateTB.Text = "";
                taskEndDateTB.Text = "";
                taskHours.Text = "";
                taskMins.Text = "";
                taskSpendHours.Text = "";
                taskSpendMins.Text = "";
            }
            doDelete = false;
        }

        private void ReDrow()
        {
            flag = true;
            TaskList.Clear();
            TaskList = DataBase.Gets();
            TaskListBox.ItemsSource = TaskList;
            flag = false;
        }
        private void before()
        {
            beforeTime = System.DateTime.Now;
            int num = TaskListBox.Items.Count;
            
            for (int i=0;i<num;i++)
            {
                mas[i] = 0;
                Task temp = (Task)TaskListBox.Items[i];
                if (temp.isRun)
                {   
                    mas[i] = 1;
                    if (temp!=null)
                    {
                        curTime[i] = new myTime();
                        TimeSpan delta = System.DateTime.Now.Subtract(temp.StartTime);
                        curTime[i].hour = delta.Hours;
                        curTime[i].min = delta.Minutes;
                        curTime[i].sec = delta.Seconds;
                    }
                }
            }
        }
        private void after() 
        {
            TimeSpan afterTime = System.DateTime.Now.Subtract(beforeTime);
            int num = TaskListBox.Items.Count;
            for (int i = 0; i < num; i++)
            {
                if (!doDelete || doDelete && i<deleteIndex)
                {
                    if (mas[i] == 1)
                    {
                        Task tttp = (Task)TaskListBox.Items[i];
                        tttp.isRun = true;

                        tttp.StartTime -= new TimeSpan(curTime[i].hour, curTime[i].min, curTime[i].sec);
                        tttp.StartTime -= afterTime;

                       
                    }
                }
                else 
                    if (doDelete)
                    {
                        if (i == deleteIndex)
                            continue;
                        else if (i>deleteIndex)
                            {
                                if (mas[i] == 1)
                                {
                                    Task tttp = (Task)TaskListBox.Items[i-1];
                                    tttp.isRun = true;
                                    
                                    tttp.StartTime -= new TimeSpan(curTime[i].hour, curTime[i].min, curTime[i].sec);
                                    tttp.StartTime -= afterTime;
                                }
                            } 
                    }
            }
            ButtonEnable();
        }
        private void ButtonEnable()
        {
            CompleteButton.IsEnabled = isSelectedItem;
            Task temp = (Task) TaskListBox.SelectedItem;
            if (isSelectedItem)
            {
                if (temp != null)
                {
                    DeleteButton.IsEnabled = !temp.isRun;
                    EditButton.IsEnabled = !temp.isRun;
                    StartButton.IsEnabled = !temp.isRun;
                    PauseButton.IsEnabled = temp.isRun;
                }
            }
            else
            {
                DeleteButton.IsEnabled = isSelectedItem;
                EditButton.IsEnabled = isSelectedItem;
                StartButton.IsEnabled = isSelectedItem;
                PauseButton.IsEnabled = isSelectedItem;
            }
        }

        private void ListBoxSelectedChange()
        {
            if (!flag)
            {
                SelectedTask = (Task)TaskListBox.SelectedItem;
                taskNameTB.Text = SelectedTask.name;
                taskDefinitionTB.Text = SelectedTask.definition;
                taskStartDateTB.Text = SelectedTask.startDate.ToShortDateString();
                taskEndDateTB.Text = SelectedTask.endDate.ToShortDateString();
                taskHours.Text = SelectedTask.hours.ToString();
                taskMins.Text = SelectedTask.mins.ToString();
                taskSpendHours.Text = SelectedTask.spendHour.ToString();
                taskSpendMins.Text = SelectedTask.spendMin.ToString();
                isSelectedItem = true;
                ButtonEnable();

                if (SelectedTask.isRun)
                {
                    isGointTask = true;
                }
                UpdateStatusBar();

            }
        }
        private void TaskListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBoxSelectedChange();
            ButtonEnable();
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            Task temp = (Task)TaskListBox.SelectedItem;
            Start(temp);
        }
        private void Start(Task temp)
        {
            isGointTask = true;
            numRunTask++;

            int SelectedIndex = TaskListBox.SelectedIndex;
           
            if (temp != null)
                temp.StartTask();

            TaskListBox.SelectedIndex = SelectedIndex;
            ListBoxSelectedChange();
            TaskListBox.Focus();

            if (timeThread == null)
            {
                timeThread = new Thread(upTime);
                timeThread.Start();
            }

            ButtonEnable();
        }

        private void upTime()
        {
            if (SelectedTask != null)
            {
                while (isGointTask)
                {
                    // do you wanna see some magic?
                    Thread.Sleep(1000);
                    DateTime dt = System.DateTime.Now;
                    var dispatcher = SpendTimeBar.Dispatcher;
                    try
                    {
                        if (SelectedTask.StartTime != System.DateTime.Now.Date) // tyt should be magic.
                        {
                            t = System.DateTime.Now.Subtract(SelectedTask.StartTime);
                            if (dispatcher.CheckAccess())
                            {
                                UpdateStatusBar();
                            }
                            else
                            {
                                dispatcher.Invoke(new Action(
                                () =>
                                {
                                    UpdateStatusBar();
                                }));
                            }
                        }
                    }
                    catch (System.Threading.Tasks.TaskCanceledException)
                    {
                    }
                }
            }
        }
        private void UpdateStatusBar()
        {
            if (SelectedTask != null)
            {
                if (SelectedTask.isRun)
                {
                    t = System.DateTime.Now.Subtract(SelectedTask.StartTime);

                    if (t.Hours < 10)
                        SpendTimeBar.Text = "0" + t.Hours + ":";
                    else
                        SpendTimeBar.Text = t.Hours + ":";

                    if (t.Minutes < 10)
                        SpendTimeBar.Text += "0" + t.Minutes + ":";
                    else
                        SpendTimeBar.Text += t.Minutes + ":";

                    if (t.Seconds < 10)
                        SpendTimeBar.Text += "0" + t.Seconds;
                    else
                        SpendTimeBar.Text += t.Seconds.ToString();

                    SpendTimeBar.Text += " / ";

                    if (SelectedTask.spendHour < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendHour + ":";
                    else
                        SpendTimeBar.Text += SelectedTask.spendHour + ":";

                    if (SelectedTask.spendMin < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendMin + ":";
                    else
                        SpendTimeBar.Text += SelectedTask.spendMin + ":";

                    if (SelectedTask.spendSec < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendSec;
                    else
                        SpendTimeBar.Text += SelectedTask.spendSec.ToString();

                    SpendTimeBar.Text += " / ";

                    if (SelectedTask.hours < 10)
                        SpendTimeBar.Text += "0";
                    SpendTimeBar.Text += SelectedTask.hours + ":";

                    if (SelectedTask.mins < 10)
                        SpendTimeBar.Text += "0";
                    SpendTimeBar.Text += SelectedTask.mins + ":";

                    SpendTimeBar.Text += "00";
                }
                else
                {
                    SpendTimeBar.Text = "00";
                    SpendTimeBar.Text += ":00";
                    SpendTimeBar.Text += ":00";

                    SpendTimeBar.Text += " / ";

                    if (SelectedTask.spendHour < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendHour + ":";
                    else
                        SpendTimeBar.Text += SelectedTask.spendHour + ":";

                    if (SelectedTask.spendMin < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendMin + ":";
                    else
                        SpendTimeBar.Text += SelectedTask.spendMin + ":";

                    if (SelectedTask.spendSec < 10)
                        SpendTimeBar.Text += "0" + SelectedTask.spendSec;
                    else
                        SpendTimeBar.Text += SelectedTask.spendSec.ToString();

                    SpendTimeBar.Text += " / ";

                    if (SelectedTask.hours < 10)
                        SpendTimeBar.Text += "0";
                    SpendTimeBar.Text += SelectedTask.hours + ":";

                    if (SelectedTask.mins < 10)
                        SpendTimeBar.Text += "0";
                    SpendTimeBar.Text += SelectedTask.mins + ":";

                    SpendTimeBar.Text += "00";
                }
            }
            else
                SpendTimeBar.Text = "";
        }

        private void Pause_Click(object sender, RoutedEventArgs e)
         {
             Pause(true);
             numRunTask--;
             if (numRunTask == 0)
             {
                 isGointTask = false;
                 // unicorns, magic and rainbow!
                 timeThread.Abort();
                 timeThread = null;
             }
         }
        private void Pause(bool pause)
        {
            int SelectedIndex = TaskListBox.SelectedIndex;

            Task temp = (Task)TaskListBox.SelectedItem;
            if (temp != null && temp.isRun)
            {
                if (pause)
                    temp.PauseTask();
                else
                    temp.CompleteTask();

                TaskListBox.SelectedIndex = SelectedIndex;
                ListBoxSelectedChange();
                tabl.Pause(temp);
                forStats();
            }

            
            TaskListBox.Focus();

            if (temp != null)
                DataBase.inTime(temp);

            ButtonEnable();
        }

        private void Complete_Click(object sender, RoutedEventArgs e)
         {
             Task temp = (Task)TaskListBox.SelectedItem;
             Pause(false);

             if (temp != null)
             {
                 TimeSpan need = new TimeSpan(temp.hours, temp.mins, 0);
                 TimeSpan spend = new TimeSpan(temp.spendHour, temp.spendMin, temp.spendSec);

                 if (spend.Days == 0)
                     MessageBox.Show("Spend " + spend.ToString() + ". Evaluate " + need.ToString());
                 else
                 {
                     string str = (spend.Days * 24 + spend.Hours).ToString() + ":" + spend.Minutes + ":" + spend.Seconds;
                     MessageBox.Show("Spend " + str + ". Evaluate " + need.ToString());
                 }
                 tabl.Complete(temp);
             }
             ListBoxSelectedChange();
            numRunTask--;
            if (numRunTask == 0)
            {
                isGointTask = false;
                timeThread.Abort();
                timeThread = null;
            }
            Delete();
            if (TaskListBox.Items.Count==0)
                SpendTimeBar.Text = "";
         }
       

    }
}
